/********* WechatPlugin.m Cordova Plugin Implementation *******/

#import <Cordova/CDV.h>
#import "MMGVenderSocialManager.h"
#import "WechatPayManager.h"

@interface WechatPlugin : CDVPlugin {
    // Member variables go here.
}

- (void)login:(CDVInvokedUrlCommand*)command;
- (void)pay:(CDVInvokedUrlCommand*)command;
- (void)hasWecaht:(CDVInvokedUrlCommand*)command;
@end

@implementation WechatPlugin

- (void)login:(CDVInvokedUrlCommand*)command
{
    NSString* appId = [command.arguments mg_objectAtIndex:0];
    NSString* secret = [command.arguments mg_objectAtIndex:1];
    
    __block CDVPluginResult* pluginResult = nil;
    [[MMGVenderSocialManager sharedMMGVenderSocialManager] signInWithVenderPlatform:UMSocialPlatformType_WechatSession inViewController:self.viewController completion:^(NSString *code,NSString *userInfoJsonString) {
        if ([code intValue] == 200) {
            DLog(@"微信登录成功 USER INFO %@....",userInfoJsonString);
            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:userInfoJsonString];
        }else {
            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:userInfoJsonString];
        }
        
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        });
        
    }];
}

- (void)pay:(CDVInvokedUrlCommand*)command
{
    NSString* produceOrder = [command.arguments mg_objectAtIndex:0];
    
    DLog(@"orderJson= %@",produceOrder);
    MMGWeakSelf(weakSelf);
    __block CDVPluginResult* pluginResult = nil;
    [[WechatPayManager sharedWechatPayManager] payWithProduce:produceOrder completionBlock:^(NSString *returnKey, BOOL isFinished) {
        if (isFinished) {
            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:returnKey];
        }else {
            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:returnKey];
            //            [SVProgressHUD showErrorWithStatus:returnKey];
        }
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        });
    }];
}

- (void)hasWecaht:(CDVInvokedUrlCommand *)command
{
    __block CDVPluginResult* pluginResult = nil;
    if([WXApi isWXAppInstalled] && [WXApi isWXAppSupportApi]){
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"yes"];
    }else {
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"no"];
    }
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
    });
}

@end
